package com.sky.Task;

import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

@Component
@Slf4j
public class OrderTask {
    @Autowired
    OrderMapper orderMapper;
    /*
     * 处理15分钟内没有支付的订单
     * */
//    @Scheduled(cron = "0/5 * * * * ?")
    @Scheduled(cron = "0 * * * * ?")
    public void processTimeoutOrder(){
        log.info("定时处理超时订单{}", LocalDateTime.now());
//        获取对应订单 未支付、时间< now-15
        List<Orders> ordersList = orderMapper.getByStatusTime(Orders.PENDING_PAYMENT, LocalDateTime.now().plusMinutes(-15));

        if(ordersList!=null && ordersList.size()>0){
            for (Orders order : ordersList) {
//              取消订单，将其设置为取消状态
                order.setStatus(Orders.CANCELLED);
                order.setCancelReason("订单超时，自动取消");
                order.setCancelTime(LocalDateTime.now());
                orderMapper.update(order);
            }
        }
    }

    /*
    * 处理一直处于派送中的订单
    * */
//    @Scheduled(cron = "0/5 * * * * ?")
    @Scheduled(cron = "0 0 0  * * ?")
    public void processDeliveryOrder(){
        log.info("定时处理一直处于派送中的订单{}", LocalDateTime.now());
//        获取对应订单 未支付、时间< now-15
        List<Orders> ordersList = orderMapper.getByStatusTime(Orders.DELIVERY_IN_PROGRESS, LocalDateTime.now());
        if(ordersList!=null && ordersList.size()>0){
            for (Orders order : ordersList) {
//              修改订单状态为 已完成
                order.setStatus(Orders.COMPLETED);
                orderMapper.update(order);
            }
        }
    }
}
